package com.farm.template.service.impl;

import com.farm.template.domain.Template;
import com.farm.template.domain.TemplateDir;
import com.farm.template.domain.TemplateFile;
import com.farm.template.domain.ex.SysDir;
import com.farm.template.domain.ex.SysFile;

import org.apache.log4j.Logger;

import com.farm.template.dao.TemplatedirDaoInter;
import com.farm.template.dao.TemplatefileDaoInter;
import com.farm.template.service.TemplatefileServiceInter;
import com.farm.template.utils.FreeMarkerUtils;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.time.TimeTool;
import com.farm.parameter.FarmParameterService;
import com.farm.project.domain.ProjectActive;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：模板文件服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class TemplatefileServiceImpl implements TemplatefileServiceInter {
	@Resource
	private TemplatefileDaoInter templatefileDaoImpl;
	@Resource
	private TemplatedirDaoInter templatedirDaoImpl;
	private static final Logger log = Logger.getLogger(TemplatefileServiceImpl.class);

	@Override
	@Transactional
	public TemplateFile insertTemplatefileEntity(TemplateFile entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		entity.setText("#[NONE]");
		return templatefileDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public TemplateFile editTemplatefileEntity(TemplateFile entity, LoginUser user) {
		TemplateFile entity2 = templatefileDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setDirid(entity.getDirid());
		entity2.setTemplateid(entity.getTemplateid());
		entity2.setText(entity.getText());
		entity2.setFilename(entity.getFilename());
		entity2.setPcontent(entity.getPcontent());
		entity2.setPstate(entity.getPstate());
		entity2.setCtime(entity.getCtime());
		entity2.setEuser(entity.getEuser());
		entity2.setCuser(entity.getCuser());
		entity2.setEtime(entity.getEtime());
		templatefileDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTemplatefileEntity(String id, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		templatefileDaoImpl.deleteEntity(templatefileDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public TemplateFile getTemplatefileEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return templatefileDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createTemplatefileSimpleQuery(DataQuery query) {
		// TODO 自动生成代码,修改后请去除本注释
		DataQuery dbQuery = DataQuery.init(query, "CBTG_TEMPLATE_FILE",
				"ID,DIRID,TEMPLATEID,TEXT,FILENAME,PCONTENT,PSTATE,CTIME,EUSER,CUSER,ETIME");
		return dbQuery;
	}

	@Override
	@Transactional
	public List<TemplateFile> getTemplateFiles(String templateid) {
		List<TemplateFile> files = templatefileDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TEMPLATEID", templateid, "=")).toList());
		return files;
	}

	@Override
	@Transactional
	public void saveText(String templateFileId, String text, LoginUser user) {
		TemplateFile entity2 = templatefileDaoImpl.getEntity(templateFileId);
		entity2.setText(text);
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		templatefileDaoImpl.editEntity(entity2);
	}

	@Override
	@Transactional
	public void saveName(String templateFileId, String name, LoginUser user) {
		TemplateFile entity2 = templatefileDaoImpl.getEntity(templateFileId);
		entity2.setFilename(name);
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		templatefileDaoImpl.editEntity(entity2);
	}

	@Override
	@Transactional
	public void bindDir(String templateFileId, String templateDirId, LoginUser user) {

		if (templatedirDaoImpl.getEntity(templateDirId) == null) {
			throw new RuntimeException("the dir is not exist:" + templateDirId);
		}

		TemplateFile entity2 = templatefileDaoImpl.getEntity(templateFileId);
		entity2.setDirid(templateDirId);
		entity2.setEuser(user.getId());
		entity2.setEtime(TimeTool.getTimeDate14());
		templatefileDaoImpl.editEntity(entity2);

	}

	@Override
	@Transactional
	public SysFile runTemplate(TemplateFile file, Map<String, Object> attrs) {
		SysFile sf = new SysFile();
		String fname = FreeMarkerUtils.getTemplateString(file.getFilename(), attrs,file.getFilename());
		String content = FreeMarkerUtils.getTemplateString(file.getText(), attrs,file.getFilename());
		sf.setContent(content);
		sf.setFilename(fname);
		return sf;
	}

	@Override
	@Transactional
	public String creatSysFile(String dirPath, SysFile sfile, ProjectActive active,Template template) {
		if (dirPath == null) {
			String activepath = FreeMarkerUtils.getActiveTemplatePath(active.getId(),template.getCode());
			File file = new File(activepath);
			if (file.mkdirs()) {
				System.out.println("Directory created: " + file.getAbsolutePath());
			} else {
				System.out.println("Directory already exists or could not be created.");
			}
			dirPath = activepath;
		}
		Path filePath = Paths.get(dirPath + File.separator + sfile.getFilename()); // 文件路径
		try {
			Files.createFile(filePath); // 创建文件
			Files.write(filePath, sfile.getContent().getBytes(StandardCharsets.UTF_8));
			return filePath.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

}
